package com.example.androidlearning.sy12.sy2musicplayer;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.example.androidlearning.R;

import java.io.IOException;

public class MusicService extends Service {

    private MediaPlayer player;
    private MusicBinder binder;

    private Integer[] music;
    private int index;

    public MusicService(){
        binder= new MusicBinder();
        music = new Integer[]{
                R.raw.bocaixiaomiououtou,
        };
//        index = 0;
//        iniMediaPlayerFile(index);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        player = MediaPlayer.create(this, R.raw.bocaixiaomiououtou);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        player = MediaPlayer.create(this, R.raw.bocaixiaomiououtou);
//        player = MediaPlayer.create(this, R.raw.bocaixiaomiououtou);
//        player.start();
    }

    public class MusicBinder extends Binder{
        /**
         * 播放音乐
         */
        public void playMusic() {
            if (!player.isPlaying()) {
                //如果还没开始播放，就开始
                player.start();
            }
        }

        public boolean isPlaying(){
            return player.isPlaying();
        }

        /**
         * 暂停播放
         */
        public void pauseMusic() {
            if (player.isPlaying()) {
                //如果还没开始播放，就开始
                player.pause();
            }
        }
        /**
         * 关闭播放器
         */
        public void closeMedia() {
            if (player != null) {
                player.stop();
                player.release();
            }
        }
        /**
         * 获取歌曲长度
         **/
        public int getProgress() {

            return player.getDuration();
        }

        /**
         * 获取播放位置
         */
        public int getPlayPosition() {

            return player.getCurrentPosition();
        }
        /**
         * 播放指定位置
         */
        public void seekToPosition(int msec) {
            player.seekTo(msec);
        }
    }
    /**
     * 添加file文件到MediaPlayer对象并且准备播放音频
     */
    private void iniMediaPlayerFile(int dex) {
        //获取文件路径
        try {
            //此处的两个方法需要捕获IO异常
            //设置音频文件到MediaPlayer对象中

            player.setDataSource(String.valueOf(music[dex]));
            //让MediaPlayer对象准备
            player.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
